package com.gem.talkbase.activity;



import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.tsz.afinal.FinalBitmap;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import com.gem.talkbase.R;
import com.gem.talkbase.client.Client;
import com.gem.talkbase.util.StreamTools;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;

public class Setinformation_mydata extends Activity {

	SharedPreferences sharedPreferences,sharedPreferences1; //获得登录者的id
	private String who = null;
	FinalBitmap fb ;
	Context context; 
	String unick;
	/*------------------------------------昵称--------------------------------------*/

	private EditText nicheng;
	private String nicheng_str ;
	/*------------------------------------昵称--------------------------------------*/





	/*------------------------------------性别--------------------------------------*/

	private RadioGroup rbsex;
	private String rbsex_str = "";
	/*------------------------------------性别--------------------------------------*/



	/*------------------------------------我的个性签名--------------------------------------*/

	private EditText mysay;
	private String mysay_str;
	/*------------------------------------我的个性签名--------------------------------------*/




	/*------------------------------------保存修改按钮--------------------------------------*/
	private Button savechange;
	private String result;
	private static String URL = Client.FRAGMENT_SETTINGS_URL;
	/*------------------------------------保存修改按钮--------------------------------------*/
    ImageView faceView;




	/*------------------------------------接受消息并更新UI--------------------------------------*/
	private static final int SET = 1 ;

	private static final int ERROR = 0 ;
	private Handler handler = new Handler(){

		@Override

		public void handleMessage(Message msg) {

			switch(msg.what){

			case SET:

				Toast.makeText(Setinformation_mydata.this, "更新成功！", 0).show();
				
				SharedPreferences sharedPreferences1 = getSharedPreferences(Client.RGISTER_UNICK, MODE_PRIVATE); 
				Editor editor = sharedPreferences1.edit();//获取编辑器 
				editor.putString("user_unick", unick);  //注册电话
				editor.commit();//提交修改 ==================================
				Intent intent= new Intent(Setinformation_mydata.this,MainActivity.class);
				intent.putExtra("user_unick",nicheng_str);
				startActivity(intent);
				finish();

				break ;

			case ERROR:

				Toast.makeText(getApplicationContext(), "更新失败!",Toast.LENGTH_SHORT).show();

				break ;

			}

		}



	};

	/*------------------------------------接受消息并更新UI--------------------------------------*/

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.setinformation_mydata);
		//获得登录者的信息
		sharedPreferences =Setinformation_mydata.this.getSharedPreferences(Client.SAVE_USER,Setinformation_mydata.this.MODE_PRIVATE);
		String userid = sharedPreferences.getString("userid", ""); 
		
		sharedPreferences1 =Setinformation_mydata.this.getSharedPreferences(Client.RGISTER_STRING,Setinformation_mydata.this.MODE_PRIVATE);
		String userid1 = sharedPreferences1.getString("user_id", ""); 
		if (userid.length()==0) {
			who = userid1;
			System.out.println(who+"========================userid1");
		}else {
			who = userid;
		}
		
		fb = FinalBitmap.create(context);
		
		/*------------------------------------昵称--------------------------------------*/

		nicheng = (EditText) findViewById(R.id.nicheng);
//========================================得到头像===========================================
		faceView=(ImageView)findViewById(R.id.face);
		
		Intent intent2=getIntent();
		String imageString=intent2.getStringExtra("image");
		
		
		/*------------------------------------性别--------------------------------------*/

		rbsex = (RadioGroup)this.findViewById(R.id.rbsex);
		//绑定一个匿名监听器
		rbsex.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(RadioGroup arg0, int arg1) {
				// TODO Auto-generated method stub
				//获取变更后的选中项的ID
				int radioButtonId = arg0.getCheckedRadioButtonId();
				//根据ID获取RadioButton的实例
				RadioButton rb = (RadioButton)Setinformation_mydata.this.findViewById(radioButtonId);
				//更新文本内容，以符合选中项
				rbsex_str = replaceBlank(rb.getText().toString());
			}
		});
		/*------------------------------------性别--------------------------------------*/


		/*------------------------------------我的个性签名--------------------------------------*/

		mysay = (EditText) findViewById(R.id.mysay);


		/*------------------------------------我的个性签名--------------------------------------*/

		/*------------------------------------接受从主页面来的消息，并给相应的选项设置--------------------------------------*/

		Bundle extras = getIntent().getExtras();
		unick = extras.getString("nicheng");//获得从主页面传来的昵称
		String hh2 = extras.getString("sex");//。。。性别
		String hh3 = extras.getString("mysay");//。。。我的个性签名
		String im=extras.getString("image");
		String imageString1 =Client.Image_URL+im+".png";
		fb.display(faceView,imageString1);
		nicheng.setText(unick);//把主页面的昵称显示在页面上
		if(hh2.equals("男")){//。。性别。。。
			RadioButton	radioButton = (RadioButton) findViewById(R.id.rbtmale);
			radioButton.setChecked(true);
		}else{
			RadioButton	radioButton = (RadioButton) findViewById(R.id.rbtfemale);
			radioButton.setChecked(true);
		}
		mysay.setText(hh3);//。。我的签名。。

		/*------------------------------------接受从主页面来的消息，并给相应的选项设置--------------------------------------*/
		/*------------------------------------保存修改按钮--------------------------------------*/
		savechange = (Button) findViewById(R.id.savechange); 
		savechange.setOnClickListener( new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				/*-----------------------------------获得昵称------------------------------------*/
				nicheng_str = replaceBlank(nicheng.getText().toString());

				/*------------------------------------获得我的个性签名-------------------------------------*/
				mysay_str = replaceBlank(mysay.getText().toString());
				/*------------------------------------子线程提交数据-------------------------------------*/
				new Thread(new Runnable() {
					public void run(){
						try {
							HttpClient client = new DefaultHttpClient();

							//提交数据的路径
							HttpPost httpPost =new HttpPost(URL);

							httpPost.addHeader("charset", HTTP.UTF_8);
							//httpPost.setHeader("Content-Type", "content-type:application/x-www-form-urlencoded");
							//httpPost.addHeader("Content-Type", "text/html");
							//指定要提交数据的实体
							List<NameValuePair> parameters = new ArrayList<NameValuePair>();

							parameters.add( new BasicNameValuePair("nicheng", URLEncoder.encode(nicheng_str,"utf-8")));//昵称提交到服务器

							parameters.add( new BasicNameValuePair("xingbie", URLEncoder.encode(rbsex_str,"utf-8")));//性别。。。。

							parameters.add( new BasicNameValuePair("mysay", URLEncoder.encode(mysay_str,"utf-8")));//我的个性签名。。。。

							parameters.add( new BasicNameValuePair("username", who));//我的唯一id。。。。

							parameters.add( new BasicNameValuePair("act", "act_mydata"));//提交 到服务器的if判断。。。。

							httpPost.setEntity(new UrlEncodedFormEntity(parameters,"utf-8"));
							//敲回车
							HttpResponse response = client.execute(httpPost);
							int code = response.getStatusLine().getStatusCode();//获得返回码，为200是则表示提交且返回成功
							System.out.println("code..madata........."+code);

							if (code == 200) {


								InputStream is = response.getEntity().getContent();
								result = StreamTools.readInputStream(is); //获取从服务器拿到的数据
								System.out.println("result..<><><><><>..."+result);
								//请求成功则返回的文本信息
								Message msg = new Message() ;
								if(result!=null){ //如果拿到的为真，则打印一个toase
									if(result.equals("true")){
										msg.what = SET ;
										Setinformation_mydata.this.handler.sendMessage(msg);
									}else{
										msg.what = ERROR ;
										Setinformation_mydata.this.handler.sendMessage(msg);
									}
								}else{
									msg.what = ERROR ;
									Setinformation_mydata.this.handler.sendMessage(msg);
								}

							}  

						} catch (UnsupportedEncodingException e) {

							e.printStackTrace();

						} catch (ClientProtocolException e) {

							e.printStackTrace();

						} catch (IOException e) {

							e.printStackTrace();

						}

					}


				}).start();
			};
		});
		/*------------------------------------保存修改按钮-------------------------------------*/
	}
	/*------------------------------------去除空格，回车，换行--------------------------------------*/	
	public static String replaceBlank(String str) {  
		String dest = "";  
		if (str!=null) {  
			Pattern p = Pattern.compile("\\s*|\t|\r|\n");  
			Matcher m = p.matcher(str);  
			dest = m.replaceAll("");  
		}  
		return dest;  
	}



	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		//Setinformation_mydata.this.finish();
	}

}
